<template>
  <a-form
      :model="form"
      :rules="rules"
      ref="formRef"
      layout="vertical"
  >
    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="First name" name="first_name">
          <a-input v-model:value="form.first_name" class="custom-input" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Last name" name="last_name">
          <a-input v-model:value="form.last_name" class="custom-input" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-form-item label="Phone Number" name="phone">
      <PhoneNumberInput
          :initialPhoneNumber="form.phone"
          :initialCountryCode="form.countryCode"
          @update:phoneData="handlePhoneData"
      />

      <div class="form-tip">
        We ask for your phone number just incase we need to reach you for any reason regarding your order with
        duonin.com. We do not rent, share, or sell your personal information. Ever.
      </div>
    </a-form-item>

    <a-form-item label="Address Line 1" name="address">
      <a-auto-complete
          v-model:value="form.address"
          :options="addressOptions"
          placeholder="Please Enter Your Address"
          @search="querySearchAsync"
          @select="autocompleteSelect"
          class="custom-input"
      />
      <div class="form-tip">
        Example: Street, Apartment, suite, building, floor, etc. (38 Skillman St, Apt B6)
      </div>
      <div class="form-warning">
        Note: We're not able to deliver the goods to the Canary Islands，Ceuta and Melilla at the moment, sorry
        for the inconvenience.
      </div>
    </a-form-item>

    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="Recipient Country/Region" name="county">
          <a-select
              v-model:value="form.county"
              @change="changeCountry"
              placeholder="please select Country/Region"
              class="custom-input"
              :options="countryList"
              :field-names="{ label: 'label', value: 'label' }"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="State/Province/Region" name="province">
          <a-input v-model:value="form.province" class="custom-input" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-row :gutter="16">
      <a-col :span="12">
        <a-form-item label="City" name="city">
          <a-input v-model:value="form.city" class="custom-input" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="Zip/Postal Code" name="zipcode">
          <a-input v-model:value="form.zipcode" class="custom-input" :maxlength="8"/>
        </a-form-item>
      </a-col>
    </a-row>

    <a-form-item v-if="showDefaultSwitch">
      <a-switch v-model:checked="defaultSet" @change="changeDefaultSet">
        <template #checkedChildren>Default</template>
        <template #unCheckedChildren>Set as Default</template>
      </a-switch>
    </a-form-item>

    <div class="form-actions">
      <a-button @click="handleCancel">Cancel</a-button>
      <a-button type="primary" @click="handleSave" :loading="saveLoading">Save</a-button>
    </div>
  </a-form>
</template>

<script setup>
import {ref, reactive, onMounted, defineProps, defineEmits, watch} from 'vue';
import PhoneNumberInput from "@/components/PhoneNumberInput.vue";
import {getGoogleMap, getMapInfo} from "@/api";
import {countries} from '@/assets/country/country.ts';
import { message } from 'ant-design-vue';
import { Local } from "@/utils/storage.ts";
import { addAddress as addUserAddress, editAddress as editUserAddress } from "@/api/user";

const props = defineProps({
  // 表单初始数据
  initialData: {
    type: Object,
    default: () => ({
      last_name: '',
      first_name: '',
      name: '',
      address: '',
      county: 'United States',
      province: '',
      city: '',
      zipcode: '',
      phone: '',
      countryCode: '+1',
      country_code: 'US',
      is_default: 0
    })
  },
  // 是否显示默认地址切换
  showDefaultSwitch: {
    type: Boolean,
    default: true
  },
  // 默认地址初始值
  defaultAddress: {
    type: Boolean,
    default: false
  },
  // 是否正在编辑地址
  isEditing: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits([
  'update:data',
  'update:isDefault',
  'update:isValid',
  'update:phoneValid',
  'save-success',
  'cancel'
]);

// 表单数据
const form = ref({...props.initialData});
// 保存按钮加载状态
const saveLoading = ref(false);
// 电话验证状态
const isPhoneValid = ref(false);

// 监听传入数据变化
watch(() => props.initialData, (newValue) => {
  if (newValue) {
    form.value = {...newValue};
    // 确保country_code有值，如果没有则根据county设置
    if (!form.value.country_code && form.value.county) {
      const selectedCountry = countryList.value.find(item => item.label === form.value.county);
      if (selectedCountry) {
        form.value.country_code = selectedCountry.value;
        // 手动触发一次表单数据更新
        setTimeout(() => {
          emitUpdateForm();
        }, 0);
      }
    }
  }
}, {deep: true});

// 表单引用
const formRef = ref(null);

// 默认地址
const defaultSet = ref(props.defaultAddress);

watch(() => props.defaultAddress, (newValue) => {
  defaultSet.value = newValue;
});

// 地址自动完成选项
const addressOptions = ref([]);

// 国家列表
const countryList = ref([]);

// 表单校验规则
const rules = {
  first_name: [
    {required: true, message: 'Your First name can\'t be empty', trigger: 'blur'},
  ],
  last_name: [
    {required: true, message: 'Your Last name can\'t be empty', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: 'Your Phone Number can\'t be empty', trigger: 'blur'},
  ],
  address: [
    {required: true, message: 'Your Address can\'t be empty', trigger: 'blur'},
  ],
  county: [
    {required: true, message: 'Your County can\'t be empty', trigger: 'blur'},
  ],
  province: [
    {required: true, message: 'Your Province can\'t be empty', trigger: 'blur'},
  ],
  city: [
    {required: true, message: 'Your City can\'t be empty', trigger: 'blur'},
  ],
  zipcode: [
    {required: true, message: 'Your Zipcode can\'t be empty', trigger: 'blur'},
  ],
};

// 监听表单数据变化并向父组件发送更新
watch(form, (newValue) => {
  // 这里不直接触发事件，而是使用函数防抖处理，避免频繁更新
  // 由于这是可能导致循环问题的主要原因，暂时注释掉
  // emit('update:data', newValue);
}, {deep: true});

// 特别监听county字段的变化
watch(() => form.value.county, (newValue, oldValue) => {
  if (newValue && newValue !== oldValue) {
    const selectedCountry = countryList.value.find(item => item.label === newValue);
    if (selectedCountry) {
      form.value.country_code = selectedCountry.value;
    } else {
      form.value.country_code = 'US';
    }
    // 通知父组件数据已更新
    emitUpdateForm();
  }
});

// 特别监听address字段的变化
watch(() => form.value.address, (newValue, oldValue) => {
  if (newValue !== oldValue) {
    // 通知父组件地址已更新
    emitUpdateForm();
  }
});

// 添加一个防抖处理的辅助函数和状态
const emitUpdateForm = () => {
  // 确保country_code有值
  if (!form.value.country_code && form.value.county) {
    const selectedCountry = countryList.value.find(item => item.label === form.value.county);
    if (selectedCountry) {
      form.value.country_code = selectedCountry.value;
    } else {
      form.value.country_code = 'US';
    }
  }

  emit('update:data', form.value);
};

// 表单中各个字段变化的处理函数，集中处理避免循环更新
const updateFormField = (fieldName, value) => {
  if (form.value[fieldName] !== value) {
    form.value[fieldName] = value;
  }
};
// 监听默认地址设置
watch(defaultSet, (newValue) => {
  emit('update:isDefault', newValue);
});

// 更改默认地址设置
const changeDefaultSet = (value) => {
  if (value !== defaultSet.value) {
    defaultSet.value = value;

    if (value) {
      form.value.is_default = 1;
    } else {
      form.value.is_default = 0;
    }

    // 只发送默认状态变更事件，不触发完整的数据更新
    emit('update:isDefault', value);

    // 手动触发一次表单数据更新，使用setTimeout避免同步循环
    setTimeout(() => {
      emitUpdateForm();
    }, 0);
  }
};

// 国家变更处理
const changeCountry = (value) => {
  // 无条件更新，不再检查是否与当前值相同
  form.value.county = value;

  // 查找对应的国家代码
  const selectedCountry = countryList.value.find(item => item.label === value);

  // 确保country_code被正确设置
  if (selectedCountry) {
    form.value.country_code = selectedCountry.value;
  } else {
    form.value.country_code = 'US';
  }

  // 立即同步更新到父组件
  emitUpdateForm();

  // 为确保更新被正确处理，再次延迟触发
  setTimeout(() => {
    emitUpdateForm();
  }, 100);
};

// 处理手机号数据
const handlePhoneData = (phoneData) => {
  if (phoneData && phoneData.isValid) {
    // 不再直接修改form，而是记录有效状态
    emit('update:phoneValid', true);

    // 如果电话号码有变化才更新
    const newPhone = phoneData.data.phoneNumber;
    const newCountryCode = phoneData.data.countryCode;

    if (form.value.phone !== newPhone) {
      form.value.phone = newPhone;
    }

    if (form.value.countryCode !== newCountryCode) {
      form.value.countryCode = newCountryCode;
    }

    // 发送一个更新事件，但不触发watch
    setTimeout(() => {
      emitUpdateForm();
    }, 0);
  } else {
    emit('update:phoneValid', false);
  }
};

// 异步获取地址建议
const querySearchAsync = async (queryString) => {
  if (!queryString || queryString.length < 1) return [];

  // 确保用户输入的值被保存到表单中
  form.value.address = queryString;

  try {
    const {data} = await getGoogleMap({
      page: 1,
      page_size: 10,
      address: queryString
    });

    const predictions = JSON.parse(data).predictions || [];
    addressOptions.value = predictions.map(pred => ({
      value: pred.description,
      description: pred.description,
      place_id: pred.place_id,
      structured_formatting: pred.structured_formatting
    }));
    return addressOptions.value;
  } catch (error) {
    console.error('Address request failed:', error);
    return [];
  }
};

// 自动完成选择处理
const autocompleteSelect = (value, option) => {
  // 使用完整的地址描述而不仅仅是main_text
  form.value.address = value;
  getAddressDetails();
};

// A辅助方法：获取地址详情
const getAddressDetails = async () => {
  const addressParams = {
    page: 1,
    page_size: 10,
    address: form.value.address,
  };
  try {
    const res = await getMapInfo(addressParams);
    if (res.code !== 200) {
      throw new Error(`Failed to fetch address suggestions with code: ${res.code}`);
    }
    if (!Array.isArray(res.data) || res.data.length === 0) {
      return;
    }
    // 创建临时对象，收集所有变更
    const updates = {};

    res.data.forEach(item => {
      if (Array.isArray(item.types) && item.types.length > 0) {
        if (item.types.includes('postal_code')) {
          updates.zipcode = item.long_name;
        } else if (item.types.includes('administrative_area_level_1')) {
          updates.province = item.long_name;
        } else if (item.types.includes('sublocality_level_1')) {
          updates.city = item.long_name;
        } else if (item.types.includes('locality')) {
          updates.city = item.long_name;
        }
      }
    });

    // 一次性应用所有变更
    if (Object.keys(updates).length > 0) {
      form.value = {...form.value, ...updates};

      // 手动触发一次表单数据更新
      setTimeout(() => {
        emitUpdateForm();
      }, 0);
    }
  } catch (error) {
    console.error('Error fetching address suggestions:', error);
  }
};

// 处理保存按钮点击
const handleSave = async () => {
  // if(form.value.phone) {
  //   message.error("The format of the phone number is incorrect");
  //   return;
  // }

  // 确保姓名和手机号被正确设置
  form.value.name = `${form.value.first_name} ${form.value.last_name}`.trim();
  form.value.zip_code = form.value.zipcode;

  // 确保country_code有值
  if (!form.value.country_code && form.value.county) {
    // 从国家列表中查找对应的country_code
    const countryList = countries.filter(c => c.status === 'assigned');
    const selectedCountry = countryList.find(c => c.name === form.value.county);
    if (selectedCountry) {
      form.value.country_code = selectedCountry.alpha2;
    } else {
      // 默认设置为US
      form.value.country_code = 'US';
    }
  }

  try {
    saveLoading.value = true;
    const valid = await validate();
    if (!valid) {
      saveLoading.value = false;
      return;
    }

    const submitData = { ...form.value };

    if (props.isEditing) {
      // 编辑地址
      const res = await editUserAddress(submitData);
      if (res.code === 200) {
        message.success("successfully edited");
        emit('save-success', submitData);
      } else {
        message.error(res.message || "Failed to edit address");
      }
    } else {
      // 添加地址
      const res = await addUserAddress(submitData);
      if (res.code === 200) {
        message.success("successfully saved");
        emit('save-success', {...submitData, id: res.data?.id});
      } else {
        message.error(res.message || "Failed to add address");
      }
    }
  } catch (error) {
    console.error("Error saving address:", error);
    message.error("Operation failed, please try again later");
  } finally {
    saveLoading.value = false;
  }
};

// 处理取消按钮点击
const handleCancel = () => {
  emit('cancel');
};

// 表单验证方法
const validate = async () => {
  try {
    await formRef.value.validate();
    emit('update:isValid', true);
    return true;
  } catch (error) {
    emit('update:isValid', false);
    return false;
  }
};

// 重置表单
const resetFields = () => {
  if (formRef.value) {
    formRef.value.resetFields();
    // 特别处理电话相关的字段
    form.value.phone = '';
    form.value.countryCode = '+1';
    // 通知父组件电话验证状态变更为 false
    emit('update:phoneValid', false);
    emit('update:data', form.value);
  }
};

// 提供给父组件的方法
defineExpose({
  validate,
  resetFields,
  formRef
});

// 初始化国家列表
onMounted(() => {
  // 过滤掉重复的alpha2键值，只保留status为assigned的国家
  const uniqueCountries = {};
  countries.forEach((country) => {
    if (country.status === 'assigned' && !uniqueCountries[country.alpha2]) {
      uniqueCountries[country.alpha2] = country;
    }
  });

  countryList.value = Object.values(uniqueCountries).map((country) => {
    return {
      value: country.alpha2,
      label: country.name,
      code: country.countryCallingCodes.map((code) =>
          code.startsWith("+") ? code.slice(1) : code
      )
    };
  });

  // 确保初始化时country_code有值
  if (!form.value.country_code && form.value.county) {
    const selectedCountry = countryList.value.find(item => item.label === form.value.county);
    if (selectedCountry) {
      form.value.country_code = selectedCountry.value;
      // 手动触发一次表单数据更新
      setTimeout(() => {
        emitUpdateForm();
      }, 0);
    }
  }
});
</script>

<style scoped>
.custom-input {
  height: 40px;
  border-radius: 4px;
}

.form-tip {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.form-warning {
  font-size: 12px;
  color: #f56c6c;
  margin-top: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 16px;
}
</style>

<!--
使用方法:
1. 引入组件:
   import AddressForm from '@/components/common/AddressForm.vue';

2. 在模板中使用:
   <AddressForm
     ref="addressFormRef"
     :initialData="formData"
     :defaultAddress="isDefaultAddress"
     :showDefaultSwitch="true"
     :isEditing="isEditingAddress"
     @update:data="onFormDataUpdate"
     @update:isDefault="onDefaultUpdate"
     @update:phoneValid="onPhoneValidUpdate"
     @save-success="handleSaveSuccess"
     @cancel="handleCancel"
   />

3. 组件属性:
   - initialData: 表单初始数据对象
   - defaultAddress: 是否为默认地址
   - showDefaultSwitch: 是否显示默认地址切换开关
   - isEditing: 是否处于编辑模式

4. 组件事件:
   - update:data: 表单数据更新时触发
   - update:isDefault: 默认地址状态更新时触发
   - update:isValid: 表单验证状态更新时触发
   - update:phoneValid: 电话号码验证状态更新时触发
   - save-success: 保存成功时触发，返回保存的数据
   - cancel: 取消时触发

5. 组件方法:
   - validate(): 验证表单，返回Promise
   - resetFields(): 重置表单
   - formRef: 表单引用，可用于直接操作表单

6. 示例数据格式:
   {
     last_name: '',
     first_name: '',
     name: '',
     address: '',
     county: 'United States',
     province: '',
     city: '',
     zipcode: '',
     phone: '',
     countryCode: '+1',
     is_default: 0
   }
-->
